package com.dd.stack.se.stream.concurrent.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/9/28 15:01
 * @Description 类功能作用说明
 */
public class BasicReentrantLockExample {
    private final ReentrantLock lock = new ReentrantLock();
    private int count = 0;

    // 累加操作（需要加锁）
    public void increment() {
        lock.lock(); // 获取锁
        try {
            count++;
            System.out.println(Thread.currentThread().getName() + " 累加后：" + count);
        } finally {
            lock.unlock(); // 释放锁（必须在finally中，确保锁一定被释放）
        }
    }

    public static void main(String[] args) {
        BasicReentrantLockExample example = new BasicReentrantLockExample();
        // 启动5个线程并发执行累加
        for (int i = 0; i < 100; i++) {
            new Thread(example::increment, "线程" + i).start();
        }
    }
}
